﻿using System;
using UnityEngine;
using System.Collections;
using Inlycat;
using SLua;
using System.IO;





public class HotSwapManager : Singleton<HotSwapManager>
{

    LuaSvr svr;
    LuaTable self;
    LuaFunction update;

    private LuaState.LoaderDelegate LoadLuaFileDelegate
    {
        get { return LuaState.loaderDelegate; }
        set { LuaState.loaderDelegate = value; }
    }

    private HotSwapManager()
    {
        LoadLuaFileDelegate = fn =>
        {
            Debug.Log("Read Bytes From " + fn);
            return File.ReadAllBytes(Path.Combine(Application.persistentDataPath, fn));
        };
    }

    public void Init(string mainLuaFile)
    {
        svr = new LuaSvr();
        self = (LuaTable)svr.start(mainLuaFile);
        update = (LuaFunction)self["update"];

        CoroutineManager.Instance.DoAction(LuaRunner(() =>
        {
            update.call(self);
        }));
    }


    #region public api


    #endregion public api


    IEnumerator LuaRunner(Action action)
    {
        while (true)
        {
            action();
            yield return null;
        }
    }
}
